package com.itxiuyixiu.homework.admin.service;

import com.itxiuyixiu.homework.entity.dao.*;
import com.itxiuyixiu.homework.entity.dto.AcademyDto;
import com.itxiuyixiu.homework.entity.dto.MajorDto;
import com.itxiuyixiu.homework.entity.dto.StudentDto;
import com.itxiuyixiu.homework.entity.dto.TeacherDto;
import com.itxiuyixiu.homework.entity.model.Academy;
import com.itxiuyixiu.homework.entity.model.Major;
import com.itxiuyixiu.homework.entity.model.Student;
import com.itxiuyixiu.homework.entity.model.Teacher;
import com.itxiuyixiu.homework.entity.vo.AcademyVo;
import com.itxiuyixiu.homework.entity.vo.MajorVo;
import com.itxiuyixiu.homework.entity.vo.StudentVo;
import com.itxiuyixiu.homework.entity.vo.TeacherVo;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDate;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * 学生、老师、学院、专业基础信息管理
 *
 * @author 黄磊
 * @date 2020/3/9
 */
@Service
public class AdminMessageService {
    private final StudentDao studentDao;
    private final AcademyDao academyDao;
    private final MajorDao majorDao;
    private final PasswordEncoder passwordEncoder;
    private final TeacherDao teacherDao;
    private final RewardsAndPunishmentDao rewardsAndPunishmentDao;
    private final CourseRecordDao courseRecordDao;
    private final CourseDao courseDao;

    private AtomicInteger nowId = new AtomicInteger(0);

    public AdminMessageService(StudentDao studentDao, AcademyDao academyDao, MajorDao majorDao, PasswordEncoder passwordEncoder, TeacherDao teacherDao, RewardsAndPunishmentDao rewardsAndPunishmentDao, CourseRecordDao courseRecordDao, CourseDao courseDao) {
        this.studentDao = studentDao;
        this.academyDao = academyDao;
        this.majorDao = majorDao;
        this.passwordEncoder = passwordEncoder;
        this.teacherDao = teacherDao;
        this.rewardsAndPunishmentDao = rewardsAndPunishmentDao;
        this.courseRecordDao = courseRecordDao;
        this.courseDao = courseDao;
    }

    @Transactional
    public Object getStudentMessage(String studentId) {
        Optional<Student> studentOptional = studentDao.findById(studentId);
        if (!studentOptional.isPresent()) {
            return null;
        }
        Student student = studentOptional.get();
        Map<String, Object> map = new HashMap<>();
        map.put("student", student);
        map.put("rewardsAndPunishment", rewardsAndPunishmentDao.findAllByStudentId(studentId));
        map.put("courseRecord", courseRecordDao.findAllByStudentId(studentId));
        return map;
    }

    /**
     * 查询学生信息
     *
     * @param dto 查询信息（只有学号、姓名、身份证号、学院ID有用）
     * @return 学生信息
     */
    public List<StudentVo> getStudentMessage(StudentDto dto) {
        if (dto.getStudentId() != null && !"".equals(dto.getStudentId())) {
            return studentDao.findAllByStudentId(dto.getStudentId());
        } else if (dto.getStudentName() != null && !"".equals(dto.getStudentName())) {
            return studentDao.findAllByStudentName(dto.getStudentName());
        } else if (dto.getIdentityCard() != null && !"".equals(dto.getIdentityCard())) {
            return studentDao.findAllByIdentityCard(dto.getIdentityCard());
        } else if (dto.getAcademyId() != null) {
            return studentDao.findAllByAcademyId(dto.getAcademyId());
        }
        return studentDao.findAllStudents();
    }

    /**
     * 获取老师信息
     *
     * @param dto 查询信息（只有id、姓名有用）
     * @return 老师信息
     */
    public List<TeacherVo> getTeacherMessage(TeacherDto dto) {
        if (dto.getId() != null) {
            return teacherDao.findAllById(dto.getId());
        } else if (dto.getTeacherName() != null && !"".equals(dto.getTeacherName())) {
            return teacherDao.findAllByTeacherName(dto.getTeacherName());
        }
        return teacherDao.findAllTeachers();
    }

    /**
     * 查询学院信息
     *
     * @param dto 查询信息（只有id、学院名有用）
     * @return 学院信息
     */
    public List<AcademyVo> getAcademyMessage(AcademyDto dto) {
        if (dto.getId() != null) {
            return academyDao.findAllById(dto.getId());
        } else if (dto.getAcademyName() != null && !"".equals(dto.getAcademyName())) {
            return academyDao.findAllByAcademyName(dto.getAcademyName());
        }
        return academyDao.findAllAcademy();
    }

    /**
     * 查询专业信息
     *
     * @param dto 查询信息（只有id、专业名有用）
     * @return 专业信息
     */
    public List<MajorVo> getMajorMessage(MajorDto dto) {
        if (dto.getId() != null) {
            return majorDao.findAllById(dto.getId());
        } else if (dto.getMajorName() != null && !"".equals(dto.getMajorName())) {
            return majorDao.findAllByMajorName(dto.getMajorName());
        } else if (dto.getAcademyId() != null) {
            System.out.println("~~~~~~~~~~~~~~~~");
            return majorDao.findAllByAcademyId(dto.getAcademyId());
        }
        return majorDao.findAllMajor();
    }

    /**
     * 添加学生信息
     *
     * @param dto 学生信息
     * @return 状态（0-成功添加，1-学院不存在，2-专业不存在）
     */
    public int addStudentMessage(StudentDto dto) {
        Optional<Academy> academyOptional = academyDao.findById(dto.getAcademyId());
        if (!academyOptional.isPresent()) {
            return 1;
        }
        Optional<Major> majorOptional = majorDao.findById(dto.getMajorId());
        if (!majorOptional.isPresent()) {
            return 2;
        }
        Academy academy = academyOptional.get();
        Major major = majorOptional.get();
        String studentId = getStudentId(dto.getAcademyId());
        String password = passwordEncoder.encode(dto.getIdentityCard().substring(dto.getIdentityCard().length() - 6));
        Student student = StudentDto.parseStudent(dto, studentId, password, academy, major);
        studentDao.save(student);
        return 0;
    }

    /**
     * 录入老师的信息
     *
     * @param dto 老师信息
     * @return 状态（0-成功添加，1-学院不存在）
     */
    public int addTeacherMessage(TeacherDto dto) {
        Optional<Academy> academyOptional = academyDao.findById(dto.getAcademyId());
        if (!academyOptional.isPresent()) {
            return 1;
        }
        Academy academy = academyOptional.get();
        Teacher teacher = TeacherDto.parseTeacher(dto, academy);
        teacherDao.save(teacher);
        return 0;
    }

    /**
     * 添加学院信息
     *
     * @param dto 学院信息
     * @return 状态（0-添加成功，1-学院已经存在）
     */
    public int addAcademyMessage(AcademyDto dto) {
        if (academyDao.existsByAcademyName(dto.getAcademyName())) {
            return 1;
        }
        Academy academy = AcademyDto.parseAcademy(dto);
        academyDao.save(academy);
        return 0;
    }

    /**
     * 添加专业信息
     *
     * @param dto 专业信息
     * @return 状态（0-添加成功，1-学院不存在，2-专业已经存在）
     */
    public int addMajorMessage(MajorDto dto) {
        Optional<Academy> academyOptional = academyDao.findById(dto.getAcademyId());
        if (!academyOptional.isPresent()) {
            return 1;
        }
        if (majorDao.existsByMajorName(dto.getMajorName())) {
            return 2;
        }
        Academy academy = academyOptional.get();
        Major major = MajorDto.parseMajor(dto, academy);
        majorDao.save(major);
        return 0;
    }


    /**
     * 修改学生信息
     *
     * @param studentId 学号
     * @param dto       学生信息
     * @return 状态（0-成功修改，1-学生不存在，2-学院不存在，3-专业不存在）
     */
    public int modifyStudentMessage(String studentId, StudentDto dto) {
        Optional<Student> studentOptional = studentDao.findById(studentId);
        if (!studentOptional.isPresent()) {
            return 1;
        }
        Optional<Academy> academyOptional = academyDao.findById(dto.getAcademyId());
        if (!academyOptional.isPresent()) {
            return 2;
        }
        Optional<Major> majorOptional = majorDao.findById(dto.getMajorId());
        if (!majorOptional.isPresent()) {
            return 3;
        }
        Academy academy = academyOptional.get();
        Major major = majorOptional.get();
        Student student = studentOptional.get();
        student.setStudentName(dto.getStudentName());
        student.setSex(dto.getSex());
        student.setIdentityCard(dto.getIdentityCard());
        student.setStudentContact(dto.getStudentContact());
        student.setAcademy(academy);
        student.setMajor(major);
        student.setStudentClass(dto.getStudentClass());
        student.setStartYear(dto.getStartYear());
        studentDao.save(student);
        return 0;
    }

    /**
     * 修改教师信息
     *
     * @param teacherId 教师id
     * @param dto       教师信息
     * @return 状态（0-成功修改，1-教师不存在，2-学院不存在）
     */
    public int modifyTeacherMessage(int teacherId, TeacherDto dto) {
        Optional<Teacher> teacherOptional = teacherDao.findById(teacherId);
        if (!teacherOptional.isPresent()) {
            return 1;
        }
        Optional<Academy> academyOptional = academyDao.findById(dto.getAcademyId());
        if (!academyOptional.isPresent()) {
            return 2;
        }
        Teacher teacher = teacherOptional.get();
        Academy academy = academyOptional.get();
        teacher.setTeacherName(dto.getTeacherName());
        teacher.setTeacherMessage(dto.getTeacherMessage());
        teacher.setSex(dto.getSex());
        teacher.setIdentifyCard(dto.getIdentifyCard());
        teacher.setContract(dto.getContract());
        teacher.setAcademy(academy);
        teacherDao.save(teacher);
        return 0;
    }

    /**
     * 修改学院信息
     *
     * @param academyId 学院id
     * @param dto       学院信息
     * @return 状态（0-成功修改，1-学院不存在）
     */
    public int modifyAcademyMessage(int academyId, AcademyDto dto) {
        Optional<Academy> academyOptional = academyDao.findById(academyId);
        if (!academyOptional.isPresent()) {
            return 1;
        }
        Academy academy = academyOptional.get();
        academy.setAcademyName(dto.getAcademyName());
        academyDao.save(academy);
        return 0;
    }

    /**
     * 修改专业信息
     *
     * @param majorId 专业id
     * @param dto     专业信息
     * @return 状态（0-修改成功，1-专业不存在，2-学院不存在）
     */
    public int modifyMajorMessage(int majorId, MajorDto dto) {
        Optional<Major> majorOptional = majorDao.findById(majorId);
        if (!majorOptional.isPresent()) {
            return 1;
        }
        Optional<Academy> academyOptional = academyDao.findById(dto.getAcademyId());
        if (!academyOptional.isPresent()) {
            return 2;
        }
        Major major = majorOptional.get();
        Academy academy = academyOptional.get();
        major.setMajorName(dto.getMajorName());
        major.setAcademy(academy);
        majorDao.save(major);
        return 0;
    }

    /**
     * 删除学生（在有奖励情况、课程情况下无法删除）
     *
     * @param studentId 学号
     * @return 状态（0-成功删除，1-学生不存在，2-存在奖励记录，3-存在课程情况）
     */
    public int deleteStudent(String studentId) {
        if (!studentDao.existsById(studentId)) {
            return 1;
        }
        if (rewardsAndPunishmentDao.existsByStudentStudentId(studentId)) {
            return 2;
        }
        if (courseRecordDao.existsByStudentStudentId(studentId)) {
            return 3;
        }
        studentDao.deleteById(studentId);
        return 0;
    }

    /**
     * 删除老师（在课程存在的情况下无法删除）
     *
     * @param teacherId 教师id
     * @return 状态（0-成功删除，1-教师不存在，2-存在课程）
     */
    public int deleteTeacher(int teacherId) {
        if (!teacherDao.existsById(teacherId)) {
            return 1;
        }
        if (courseDao.existsByTeacherId(teacherId)) {
            return 2;
        }
        teacherDao.deleteById(teacherId);
        return 0;
    }

    /**
     * 删除学院
     *
     * @param academyId 学院id
     * @return 状态（0-成功删除，1-学院不存在，2-存在学生，3-存在专业，4-存在老师）
     */
    public int deleteAcademy(int academyId) {
        if (!academyDao.existsById(academyId)) {
            return 1;
        }
        if (studentDao.existsByAcademyId(academyId)) {
            return 2;
        }
        if (majorDao.existsByAcademyId(academyId)) {
            return 3;
        }
        if (teacherDao.existsByAcademyId(academyId)) {
            return 4;
        }
        academyDao.deleteById(academyId);
        return 0;
    }

    /**
     * 删除专业（在专业、学生、课程存在的情况下无法删除）
     *
     * @param majorId 专业id
     * @return 状态（0-成功删除，1-专业不存在，2-存在学生，3-存在课程）
     */
    public int deleteMajor(int majorId) {
        if (!majorDao.existsById(majorId)) {
            return 1;
        }
        if (studentDao.existsByMajorId(majorId)) {
            return 2;
        }
        if (courseDao.existsByMajorId(majorId)) {
            return 3;
        }
        majorDao.deleteById(majorId);
        return 0;
    }

    /**
     * 生成学号
     *
     * @param academyId 学院id
     * @return 学号
     */
    private String getStudentId(int academyId) {
        int id = nowId.getAndIncrement();
        int year = LocalDate.now().getYear() - 2000;
        return String.format("%02d%02d%05d", year, academyId, id);
    }


}
